<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>关于我设置 - 管理面板</title>
    <meta name="turbo-cache-control" content="no-cache">
    <script defer src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@7.3.0/dist/turbo.es2017-umd.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
    <style>
        body {
            background-color: #121212;
            color: #e0e0e0;

        }

        /* navbar override removed; use global fragment styles */

        .card {
            background-color: #1e1e1e;
            border: 1px solid #333;
            margin-bottom: 20px;
        }

        .card-header {
            background-color: #252525;
            border-bottom: 1px solid #333;
            color: #fff;
        }

        .form-control, .form-select {
            background-color: #2c2c2c;
            border: 1px solid #444;
            color: #e0e0e0;
        }

        .form-control:focus, .form-select:focus {
            background-color: #2c2c2c;
            color: #e0e0e0;
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }

        .btn-primary {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }

        .btn-outline-secondary {
            color: #e0e0e0;
            border-color: #6c757d;
        }

        .btn-outline-secondary:hover {
            background-color: #6c757d;
            color: #fff;
        }

        .alert-success {
            background-color: #0f5132;
            color: #d1e7dd;
            border-color: #095c2f;
        }

        .alert-danger {
            background-color: #842029;
            color: #f8d7da;
            border-color: #6e1a22;
        }

        .CodeMirror {
            background-color: #2c2c2c;
            color: #e0e0e0;
            border: 1px solid #444;
        }

        .editor-toolbar {
            background-color: #252525;
            border: 1px solid #444;
            border-bottom: none;
        }

        .editor-toolbar a {
            color: #e0e0e0 !important;
        }

        .editor-toolbar a:hover {
            background-color: #444;
        }

        .editor-toolbar.fullscreen {
            background-color: #252525;
        }

        .CodeMirror-fullscreen {
            background-color: #2c2c2c;
        }

        .social-link-item {
            background-color: #252525;
            border: 1px solid #444;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .preview-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            margin-top: 10px;
            border: 2px solid #444;
        }

        /* 技能标签样式 */
        .skill-tag {
            display: inline-flex;
            align-items: center;
            background-color: #3a3a3a;
            color: #e0e0e0;
            padding: 5px 10px;
            border-radius: 15px;
            margin-right: 5px;
            margin-bottom: 5px;
            font-size: 0.9em;
        }

        .skill-tag .btn-close {
            margin-left: 8px;
            font-size: 0.7em;
        }
    </style>
</head>
<body>
<!-- 导航栏替换为统一片段 -->
<div th:replace="~{fragments/navbar :: navbar}"></div>

<div class="container mt-4">
    <h2 class="mb-4"><i class="bi bi-person-circle"></i> 关于我设置</h2>

    <div th:if="${successMessage}" class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill"></i> <span th:text="${successMessage}"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i> <span th:text="${errorMessage}"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>

    <form th:action="@{/admin/about}" method="post" enctype="multipart/form-data">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">基本信息</h5>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="aboutName" class="form-label">名称</label>
                        <input type="text" class="form-control" id="aboutName" name="aboutName" th:value="${aboutName}"
                               placeholder="输入您的名称">
                    </div>
                    <div class="col-md-6">
                        <label for="avatarFile" class="form-label">头像</label>
                        <input type="file" class="form-control" id="avatarFile" name="avatarFile" accept="image/*">
                        <input type="hidden" name="aboutAvatar" th:value="${aboutAvatar}">
                        <div class="form-text text-muted">如果不上传新图片，将保留现有头像。</div>
                        <div class="mt-2">
                            <img id="avatarPreview"
                                 th:src="${aboutAvatar != null && !aboutAvatar.isEmpty() ? aboutAvatar : 'https://via.placeholder.com/100'}"
                                 class="preview-avatar" alt="头像预览">
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="aboutBio" class="form-label">简介</label>
                    <textarea class="form-control" id="aboutBio" name="aboutBio" rows="2" placeholder="简短的自我介绍"
                              th:text="${aboutBio}"></textarea>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">技能标签</h5>
            </div>
            <div class="card-body">
                <label class="form-label">技能</label>
                <div id="skills-container" class="mb-2 border rounded p-2"
                     style="min-height: 40px; border-color: #444 !important;">
                </div>
                <div class="input-group">
                    <input type="text" id="skill-input" class="form-control" placeholder="例如：Java">
                    <button type="button" class="btn btn-primary" id="add-skill-btn"><i class="bi bi-plus"></i> 添加
                    </button>
                </div>
                <input type="hidden" id="aboutSkills" name="aboutSkills" th:value="${aboutSkills}">
                <div class="form-text text-muted">输入技能后点击“添加”按钮或按回车键。</div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">社交链接</h5>
                <button type="button" class="btn btn-sm btn-primary" id="addSocialLink">
                    <i class="bi bi-plus-circle"></i> 添加链接
                </button>
            </div>
            <div class="card-body">
                <div id="socialLinksContainer">
                </div>
                <input type="hidden" id="aboutSocialLinks" name="aboutSocialLinks" th:value="${aboutSocialLinks}">
                <div class="form-text text-muted">常用图标: bi-github, bi-linkedin, bi-twitter, bi-facebook,
                    bi-instagram, bi-youtube, bi-globe, bi-envelope
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">详细内容</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="aboutContent" class="form-label">详细内容（支持Markdown）</label>
                    <textarea class="form-control" id="aboutContent" name="aboutContent" rows="10"
                              th:text="${aboutContent}"></textarea>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-between mb-5">
            <a href="/admin" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> 返回管理面板</a>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> 保存设置</button>
        </div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
<script>
    // 全局EasyMDE实例管理
    let easyMDEInstance = null;

    // 管理页面初始化函数
    window.initializeAdminPage = function() {
        console.log("开始初始化管理页面...");
        
        // 多次尝试初始化，确保在服务器环境下也能正常工作
        const attemptInit = (attempt = 1) => {
            console.log(`管理页面初始化尝试 ${attempt}`);
            
            // 移除旧的初始化标记，允许重新初始化
            document.body.removeAttribute('data-admin-page-initialized');
            
            if (initializeAboutSettings()) {
                console.log('管理页面初始化成功');
                document.body.setAttribute('data-admin-page-initialized', 'true');
            } else if (attempt < 5) {
                console.log(`管理页面初始化失败，${300 * attempt}ms后重试`);
                setTimeout(() => attemptInit(attempt + 1), 300 * attempt);
            } else {
                console.error('管理页面初始化最终失败');
            }
        };
        
        attemptInit();
    };
    
    function initializeAboutSettings() {
        console.log('开始初始化关于页面设置...');
        let initSuccess = true;
        
        const editorElement = document.getElementById('aboutContent');
        if (!editorElement) {
            console.log("未找到编辑器元素，跳过EasyMDE初始化");
            initSuccess = false;
        } else {

        // 如果旧的编辑器实例存在，先销毁它
        if (easyMDEInstance) {
            try {
                easyMDEInstance.toTextArea();
                easyMDEInstance = null;
                console.log("清理了旧的EasyMDE实例");
            } catch (e) {
                console.warn("清理EasyMDE实例时出错:", e);
                easyMDEInstance = null;
            }
        }

            // 初始化Markdown编辑器
            try {
                if (typeof EasyMDE === 'undefined') {
                    console.error('EasyMDE 库未加载');
                    initSuccess = false;
                } else {
                    easyMDEInstance = new EasyMDE({
                        element: editorElement,
                        spellChecker: false,
                        autosave: {
                            enabled: true,
                            delay: 1000,
                            uniqueId: 'aboutContent'
                        },
                        toolbar: [
                            'bold', 'italic', 'heading', '|',
                            'quote', 'unordered-list', 'ordered-list', '|',
                            'link', 'image', '|',
                            'preview', 'side-by-side', 'fullscreen', '|',
                            'guide'
                        ]
                    });
                    console.log("EasyMDE编辑器初始化成功");
                }
            } catch (e) {
                console.error("EasyMDE初始化失败:", e);
                initSuccess = false;
            }
        }

        // 头像预览
        const avatarFileInput = document.getElementById('avatarFile');
        if (avatarFileInput && !avatarFileInput.hasAttribute('data-listener-added')) {
            avatarFileInput.addEventListener('change', function (event) {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        document.getElementById('avatarPreview').src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
            avatarFileInput.setAttribute('data-listener-added', 'true');
        }

        // 技能标签管理
        try {
            initializeSkillsManagement();
            console.log('技能标签管理初始化成功');
        } catch (e) {
            console.error('技能标签管理初始化失败:', e);
            initSuccess = false;
        }

        // 社交链接管理
        try {
            initializeSocialLinksManagement();
            console.log('社交链接管理初始化成功');
        } catch (e) {
            console.error('社交链接管理初始化失败:', e);
            initSuccess = false;
        }
        
        console.log('关于页面设置初始化完成，结果:', initSuccess);
        return initSuccess;
    }

    function initializeSkillsManagement() {
        console.log('开始初始化技能标签管理...');
        const skillsInput = document.getElementById('aboutSkills');
        const skillInput = document.getElementById('skill-input');
        const addSkillBtn = document.getElementById('add-skill-btn');
        const skillsContainer = document.getElementById('skills-container');
        
        if (!skillsInput || !skillInput || !addSkillBtn || !skillsContainer) {
            console.error('技能标签管理所需元素未找到');
            return false;
        }
        
        let skills = skillsInput.value ? skillsInput.value.split(',').map(s => s.trim()).filter(Boolean) : [];

        const renderSkills = () => {
            skillsContainer.innerHTML = '';
            skills.forEach(skill => {
                const tag = document.createElement('span');
                tag.className = 'skill-tag';
                tag.textContent = skill;
                const closeBtn = document.createElement('button');
                closeBtn.type = 'button';
                closeBtn.className = 'btn-close btn-close-white';
                closeBtn.setAttribute('aria-label', 'Close');
                closeBtn.addEventListener('click', () => {
                    skills = skills.filter(s => s !== skill);
                    skillsInput.value = skills.join(',');
                    renderSkills();
                });
                tag.appendChild(closeBtn);
                skillsContainer.appendChild(tag);
            });
        };

        const addSkill = () => {
            const newSkill = skillInput.value.trim();
            if (newSkill && !skills.includes(newSkill)) {
                skills.push(newSkill);
                skillsInput.value = skills.join(',');
                renderSkills();
            }
            skillInput.value = '';
            skillInput.focus();
        };

        // 防止重复绑定事件
        if (!addSkillBtn.hasAttribute('data-listener-added')) {
            addSkillBtn.addEventListener('click', addSkill);
            addSkillBtn.setAttribute('data-listener-added', 'true');
        }
        
        if (!skillInput.hasAttribute('data-listener-added')) {
            skillInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addSkill();
                }
            });
            skillInput.setAttribute('data-listener-added', 'true');
        }

        renderSkills();
        console.log('技能标签管理初始化完成');
        return true;
    }

    function initializeSocialLinksManagement() {
        console.log('开始初始化社交链接管理...');
        const socialLinksInput = document.getElementById('aboutSocialLinks');
        const socialLinksContainer = document.getElementById('socialLinksContainer');
        const addSocialLinkBtn = document.getElementById('addSocialLink');
        
        if (!socialLinksInput || !socialLinksContainer || !addSocialLinkBtn) {
            console.error('社交链接管理所需元素未找到');
            return false;
        }

        function parseSocialLinks() {
            const linksValue = socialLinksInput.value;
            if (!linksValue) return [];
            try {
                return linksValue.split(',').map(link => {
                    const parts = link.trim().split('|');
                    if (parts.length >= 2) {
                        // 兼容两种格式：name|url|icon 或 name|url
                        return {
                            name: parts[0].trim(),
                            url: parts[1].trim(),
                            icon: parts.length >= 3 ? parts[2].trim() : 'bi-link'
                        };
                    }
                    return null;
                }).filter(link => link !== null);
            } catch (e) {
                console.error('解析社交链接时出错:', e);
                return [];
            }
        }

        function updateSocialLinksValue() {
            const linkItems = document.querySelectorAll('.social-link-item');
            const links = [];
            linkItems.forEach(item => {
                const nameInput = item.querySelector('.link-name');
                const urlInput = item.querySelector('.link-url');
                const iconInput = item.querySelector('.link-icon');
                if (nameInput.value && urlInput.value) {
                    links.push(`${nameInput.value}|${urlInput.value}|${iconInput.value}`);
                }
            });
            socialLinksInput.value = links.join(',');
        }

        function addSocialLinkItem(link = {name: '', url: '', icon: 'bi-link'}) {
            const linkItem = document.createElement('div');
            linkItem.className = 'social-link-item';
            linkItem.innerHTML = `
                    <div class="row mb-2">
                        <div class="col-md-4">
                            <label class="form-label">名称</label>
                            <input type="text" class="form-control link-name" value="${link.name}" placeholder="例如：GitHub">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">图标</label>
                            <input type="text" class="form-control link-icon" value="${link.icon}" placeholder="例如：bi-github">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <button type="button" class="btn btn-danger remove-link"><i class="bi bi-trash"></i> 删除</button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <label class="form-label">URL</label>
                            <input type="text" class="form-control link-url" value="${link.url}" placeholder="例如：https://github.com/yourusername">
                        </div>
                    </div>
                `;

            linkItem.querySelector('.remove-link').addEventListener('click', function () {
                linkItem.remove();
                updateSocialLinksValue();
            });

            const inputs = linkItem.querySelectorAll('input');
            inputs.forEach(input => {
                input.addEventListener('input', updateSocialLinksValue);
            });

            socialLinksContainer.appendChild(linkItem);
        }

        // 防止重复绑定事件
        if (!addSocialLinkBtn.hasAttribute('data-listener-added')) {
            addSocialLinkBtn.addEventListener('click', function () {
                addSocialLinkItem();
            });
            addSocialLinkBtn.setAttribute('data-listener-added', 'true');
        }

        // 【关键修复】在添加新项目前，先清空容器
        socialLinksContainer.innerHTML = '';

        // 初始化现有链接
        const existingLinks = parseSocialLinks();
        console.log('解析到的社交链接:', existingLinks);
        if (existingLinks.length > 0) {
            existingLinks.forEach(link => addSocialLinkItem(link));
        } else {
            // 如果没有现有链接，添加一个空的链接项供用户填写
            addSocialLinkItem();
        }

        // 表单提交时更新值
        const form = document.querySelector('form');
        if (form && !form.hasAttribute('data-listener-added')) {
            form.addEventListener('submit', function () {
                updateSocialLinksValue();
            });
            form.setAttribute('data-listener-added', 'true');
        }
        
        console.log('社交链接管理初始化完成');
        return true;
    }
    
    // Turbo缓存前清理
    document.addEventListener('turbo:before-cache', function() {
        console.log('清理管理页面状态...');
        
        // 清理EasyMDE实例
        if (easyMDEInstance) {
            try {
                easyMDEInstance.toTextArea();
                easyMDEInstance = null;
                console.log("已清理EasyMDE实例");
            } catch (e) {
                console.warn("清理EasyMDE实例时出错:", e);
                easyMDEInstance = null;
            }
        }
        
        // 移除初始化标记
        document.body.removeAttribute('data-admin-page-initialized');
    });
    
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM加载完成，开始初始化关于我设置页面');
        if (typeof window.initializeAdminPage === 'function') {
            window.initializeAdminPage();
        } else {
            console.error('initializeAdminPage函数未定义');
        }
    });
    
    // Turbo导航时也需要初始化
    document.addEventListener('turbo:load', function() {
        console.log('Turbo导航完成，重新初始化关于我设置页面');
        if (typeof window.initializeAdminPage === 'function') {
            window.initializeAdminPage();
        }
    });
</script>

<!-- Bootstrap和Turbo处理已由turbo-fixes.js统一管理 -->
</body>
</html>